<template>
	<DialogBox v-model:visible="drawerVisible" :title="`${drawerProps.title}用户`" :width="drawerProps.width || '900px'">
		<el-form
			v-if="drawerVisible"
			ref="ruleFormRef"
			label-width="100px"
			label-suffix=" :"
			:rules="rules"
			:disabled="drawerProps.isView"
			:model="drawerProps.rowData"
			:hide-required-asterisk="drawerProps.isView"
		>
			<div class="flex">
				<div class="flex-1">
					<el-form-item label="登录账号" prop="username">
						<el-input
							v-model="drawerProps.rowData!.username"
							placeholder="请输入登录账号"
							:disabled="drawerProps.rowData!.id?true:false"
						/>
					</el-form-item>
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="drawerProps.rowData!.email" placeholder="请输入邮箱" />
					</el-form-item>
					<el-form-item label="手机号" prop="mobile">
						<el-input v-model="drawerProps.rowData!.mobile" placeholder="请输入手机号" />
					</el-form-item>
					<el-form-item label="角色" prop="roleId">
						<el-select v-model="drawerProps.rowData!.roleId" placeholder="请选择角色" class="w-full" :disabled="isLoginUser">
							<el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="公司" prop="company">
						<el-input v-model="drawerProps.rowData!.company" placeholder="公司名称" />
					</el-form-item>
					<el-form-item label="状态" prop="status">
						<el-switch
							v-model="drawerProps.rowData!.status"
							:active-value="'1'"
							:inactive-value="'0'"
							:disabled="isLoginUser"
						></el-switch>
					</el-form-item>
					<el-form-item v-if="!isLoginUser" prop="tokenExp">
						<template #label>
							<div>
								<ElTooltip raw-content>
									<template #content>
										<div>授权Token使用时间期限</div>
									</template>
									<i class="iconfont iconhelp-circle pl-2"></i>
								</ElTooltip>
								期限 :
							</div>
						</template>
						<div class="flex w-full">
							<el-input v-model="drawerProps.rowData!.tokenExp" placeholder="请输入授权期限" type="number">
								<template #suffix>天</template>
							</el-input>
						</div>
					</el-form-item>
					<el-form-item v-if="!isLoginUser" v-show="drawerProps.rowData!.generateToken" label="授权Token" prop="generateToken">
						<el-link v-copy="drawerProps.rowData!.generateToken" title="点击复制Token" :underline="false">
							{{ drawerProps.rowData!.generateToken }}
						</el-link>
					</el-form-item>
					<el-form-item label="描述" prop="description">
						<el-input v-model="drawerProps.rowData!.description" type="textarea" placeholder="请输入备注描述" />
					</el-form-item>
				</div>
				<div class="flex-1" v-if="!isLoginUser">
					<!-- <el-form-item label="分组" prop="parentId">
				<el-tree-select v-model="drawerProps.rowData!.parentId" :data="menuId" check-strictly placeholder="选择分组" clearable />
			</el-form-item> -->
					<el-form-item label="" prop="deptIds">
						<TreeFilter
							v-if="drawerVisible"
							class="h-96 w-full border"
							multiple
							:requestApi="getDeptList"
							id="id"
							label="deptName"
							:dataCallback="dataCallback"
							:defaultValue="deptId"
							:isCheckStrictly="isCheckStrictly"
							@change="changeDeptId"
							@tree-ref-mounted="isCheckStrictly = false"
						/>
					</el-form-item>
				</div>
			</div>
		</el-form>
		<template #footer>
			<el-button @click="drawerVisible = false">取消</el-button>
			<el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
		</template>
	</DialogBox>
</template>

<script setup lang="ts" name="UserDrawer">
import { getDeptList } from "@/api/modules/dept";
import { getRoleList } from "@/api/modules/role";
import { getUser } from "@/api/modules/user";
import DialogBox from "@/components/DialogBox";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { GlobalStore } from "@/stores";
import { showTips } from "@/utils/util";
import { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import { UserModel } from "../interface";
const globalStore = GlobalStore();
const isLoginUser = ref<boolean>(false);
const rules = reactive<any>({});
interface DrawerProps {
	width?: string;
	title: string;
	isView: boolean;
	rowData?: UserModel;
	api?: (params: any) => Promise<any>;
	getTableList?: () => Promise<any>;
}

// drawer框状态
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: ""
});

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps): Promise<void> => {
	drawerProps.value = params;
	if (drawerProps.value.rowData?.tokenExp) {
		drawerProps.value.rowData.tokenExp = drawerProps.value.rowData?.tokenExp / 24 / 60 / 60 / 1000;
	}
	if (params.title == "新增") {
		drawerProps.value.rowData!.status = "1";
	}
	isLoginUser.value = drawerProps.value.rowData?.id == globalStore.userInfo.userId;
	if (!isLoginUser.value) {
		rules.username = [{ required: true, message: "账号不能为空" }];
		rules.roleId = [{ required: true, message: "角色不能为空" }];
		rules.deptIds = [{ required: true, message: "用户分组不能为空" }];
	} else {
		rules.username = [{ required: true, message: "账号不能为空" }];
	}
	await getDeptId();
	await getRole();
	drawerVisible.value = true;
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			if (drawerProps.value.rowData?.tokenExp) {
				drawerProps.value.rowData.tokenExp = drawerProps.value.rowData?.tokenExp * 24 * 60 * 60 * 1000;
			}
			let { code } = await drawerProps.value.api!({
				...drawerProps.value.rowData,
				deptIds: deptId.value.toString()
			});
			let ok = showTips(code, drawerProps.value.rowData?.id ? "修改用户" : "添加用户");
			// ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
			if (ok) {
				drawerVisible.value = false;
				drawerProps.value.getTableList?.();
			}
		} catch (error) {
			console.log(error);
		}
	});
};

// dataCallback 是对于返回的表格数据做处理，
const dataCallback = (data: any) => {
	return data.records.children;
};
//获取角色分组权限
const deptId = ref<any>([]);
const isCheckStrictly = ref<boolean>();
const getDeptId = async () => {
	if (drawerProps.value.rowData) {
		let { result } = await getUser(drawerProps.value.rowData.username);
		deptId.value = result.deptIds.split(",");
		isCheckStrictly.value = true;
		drawerProps.value.rowData!.deptIds = result.deptIds;
	}
};

//勾选菜单返回数据
const changeDeptId = (data: any) => {
	deptId.value = [...data.checked, ...data.halfChecked].map((item: any) => item.id).filter((item: any) => item != "root");
	drawerProps.value.rowData!.deptIds = deptId.value.toString();
};
//获取角色列表
const roleList = ref<any>();
const getRole = async () => {
	let { result } = await getRoleList({ pageIndex: 1, pageSize: 999 });
	roleList.value = result.records;
};
defineExpose({
	acceptParams
});
</script>
